package tests;

import java.io.*;
import java.util.Scanner;

public class KnuthReader 
{
	// instance variables
	Scanner fileScan = null;
	Scanner testLength = null;
	String filepath;
	int countNames = 0;
	int countEdges = 0;
	
	// constructor
	public KnuthReader(String fileName) throws FileNotFoundException
	{
		// save filepath and name
		filepath = fileName;
		// create File object and Scanner
		File inFile = new File(fileName);
		fileScan = new Scanner(inFile);
		testLength = new Scanner(inFile);
		// determine the number of Vertices
		this.fileLength();
	}
	
	// internal method to find the number of names/cities
	private void fileLength() {
		while(testLength.hasNextLine())
			// If it is only a name, not a edge count it
			if(!testLength.nextLine().contains("["))
				countNames++;
			else
				countEdges++;
		testLength.close();
	}
	
	public int getNumOfVertices() {
		return countNames;
	}
	
	public int getNumOfEdges() {
		return countEdges;
	}	
	
	// get names
	private void addNames(UndirectedGraph un) {
		for(int i=0; i<countNames; i++) {
			String input = fileScan.nextLine();
			if(input.indexOf('"')==0)
				un.addName(input.substring(1, input.indexOf('"', 1)));
			else
				un.addName(input.trim());		
		}
	}
	
	private void addEdge(UndirectedGraph un) 
	{
		// Save the org. vertice and the destination
		String orginationVertice = "";
		String destinationVertice = "";
		// variable to hold the distance
		int distance = 0;
		
		// perform the extraction of the edges
		while(fileScan.hasNextLine()) 
		{
			String in = fileScan.nextLine();
			// Origination word.
			if(in.indexOf('"')==0)
				orginationVertice = in.substring(1, in.indexOf('"', 1));
			else
				orginationVertice = in.substring(0, in.indexOf("--",0));
			
			int nextWord = in.indexOf("--", 0)+2;
			// Destination word
			if(in.indexOf('"', nextWord)==nextWord)
				destinationVertice  = in.substring(
									in.indexOf('"',nextWord)+1, 
									in.indexOf('"',nextWord+1));
			else
			{
				destinationVertice  = in.substring(
									nextWord, 
									in.indexOf(' ',nextWord));
				destinationVertice .trim();
			}				

			distance = Integer.parseInt(in.substring(
									in.indexOf('[')+1,  
									in.indexOf(']')));
			un.addEdge(orginationVertice, 
					destinationVertice, 
					distance);
		}
	}
		
	// filepath
	public String getFilePath() {
		return filepath; 
	}
	
	// Run fileparser
	public void run(UndirectedGraph un) {
		this.addNames(un);
		this.addEdge(un);
		fileScan.close();
	}
} // end of class